<?php
include 'function.php';
$error = '';

// when login
if (isset($_POST['lname']))
{
	$conn = conn();
	$name = trim($_POST['lname']);
	$pass = trim($_POST['lpass']);
	if (!empty($name) && !empty($pass))
	{
		$esc_name = mysql_real_escape_string($name, $conn);
		$sql = "SELECT id FROM accounts WHERE email = '$esc_name' OR name = '$esc_name'";
		$result = mysql_query($sql, $conn);
		$row = mysql_fetch_assoc($result);
		if (!isset($row['id']))
		{
			$error = '邮箱/用户名不正确';
		}
		else
		{
			$esc_pass = mysql_real_escape_string($pass, $conn);
			$sql = "SELECT id FROM accounts WHERE (email = '$esc_name' OR name = '$esc_name') AND pwd = MD5('$esc_pass')";
			$result = mysql_query($sql, $conn);
			$row = mysql_fetch_assoc($result);
			if (!isset($row['id']))
			{
				$error = '密码不正确';
			}
			else
			{
				// login successful
				$_SESSION['id'] = $row['id'];
				header('Location:/');
				exit;
			}
		}
	}
	elseif (empty($name))
	{
		$error = '邮箱/用户名不能为空';
	}
	elseif (empty($pass))
	{
		$error = '密码不能为空';
	}
}
?><!DOCTYPE HTML>
<html>
	<head>
		<link rel="shortcut icon" href="favicon.ico" type="image/vnd.microsoft.icon" />
		<meta http-equiv="content-type" content="text/html; charset=utf-8" />
		<meta name="keywords" content="" />
		<meta name="description" content="" />
		<title></title>
		<link rel="stylesheet" type="text/css" href="theme.css" />
	</head>
	<body>
		<div class="wrapper">
			<div class="logo"><a href="/"><?php echo SITE;?></a></div>
			<div class="clear"></div>
			<form action="login.php" method="post"><?php if('' != $error) echo '
				<div class="reg_left"></div>
				<div class="reg_right"><span style="color:red;">'.$error.'</span></div>
				<div class="clear reg_lh"></div>
				';?><div class="reg_left">邮箱/用户名：</div>
				<div class="reg_right"><input name="lname" type="text" class="reg_input" value="<?php if(isset($name))echo $name;?>" /></div>
				<div class="clear reg_lh"></div>
				<div class="reg_left">密码：</div>
				<div class="reg_right"><input name="lpass" type="password" class="reg_input" value="<?php if(isset($pass))echo $pass;?>" /></div>
				<div class="clear reg_lh"></div>
				<div class="reg_left"></div>
				<div class="reg_right"><input type="submit" value="登录" class="reg_submit" /> 
					<a href="password.php">忘记密码？</a>
				</div>
				<div class="clear"></div>
			</form>
			<div class="reg_left"></div>
			<div class="reg_right"><div style="margin-top:40px;">还没有<?php echo SITE;?>帐号？<a href="register.php">立即注册</a></div></div>
			<div class="clear"></div>
		</div>
	</body>
</html>